package hcd.electrick;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.*;
import android.widget.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by david on 2017/1/31.
 */
public class BalanceFragment extends Fragment {


    private String[] dormList;
    private String session;

    private TextView dormLabel;
    private TextView balanceLabel;
    private TextView updateTimeLabel;

    private EditText amountText;
//    private String payMethod = "1";

    private String buildID;
    private String floorID;
    private String dormID;

    private BalanceHandler balanceHandler;
    private UserBalanceHandler userBalanceHandler;
    private PayHandler payHandler;

    private ProgressDialog loadingView;

    private int payAmount = 100;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d("balanceFragment", "onCreateView");
        getActivity().setTitle("JLUZH.Ecard");
        setHasOptionsMenu(true);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        View rootView = inflater.inflate(R.layout.fragment_banlance, container, false);

        dormList = getArguments().getStringArray("value");
        session = getArguments().getString("session");

        dormLabel = (TextView) rootView.findViewById(R.id.dorm_label);
        balanceLabel = (TextView) rootView.findViewById(R.id.balance_label);
        updateTimeLabel = (TextView) rootView.findViewById(R.id.update_time_label);

        balanceHandler = new BalanceHandler();
        userBalanceHandler = new UserBalanceHandler();
        payHandler = new PayHandler();

        loadingView = new ProgressDialog(getContext(), ProgressDialog.STYLE_SPINNER);
        loadingView.setMessage("请稍后...");

        SharedPreferences preferences = getContext().getSharedPreferences("dorm", Context.MODE_PRIVATE);
        String dormName = preferences.getString("dorm_name", null);
        if (dormName != null){
            dormLabel.setText(dormName);
            buildID = preferences.getString("build_id", "");
            floorID = preferences.getString("floor_id", "");
            dormID = preferences.getString("dorm_id", "");
            getElectrick();
        }else {
            dormLabel.setText(getString(R.string.unselected));
        }


        Button selectDormBtn = (Button) rootView.findViewById(R.id.select_dorm_btn);
        selectDormBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelectDormFragment fragment = new SelectDormFragment();
                Bundle bundle = new Bundle();
                bundle.putStringArray("value", dormList);
                bundle.putString("session", session);

                fragment.setArguments(bundle);

                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, fragment)
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .addToBackStack(null)
                        .commit();
            }
        });

        amountText = (EditText) rootView.findViewById(R.id.amount_text);
        amountText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                try{
                    int d = Integer.parseInt(s.toString());
                    if (d < 1){
                        amountText.setText("1");
                        payAmount = 1;
                    }else if (d > 1000){
                        amountText.setText("1000");
                        payAmount = 1000;
                        amountText.setSelection(4);
                    }else {
                        payAmount = d;
                    }
                }catch (Exception e){
                    amountText.setText("1");
                    payAmount = 1;
                    amountText.setSelection(1);
                }


//                String[] compo = s.toString().split("\\.");
//                if (compo.length > 1){
//                    if (compo[1].length() > 1){
//                        amountText.setText(s.subSequence(0, s.length() - 1));
//                        amountText.setSelection(s.length() - 1);
//                    }
//                }
//                if (s.toString().equals("")){
//                    amountText.setText("1");
//                    amountText.setSelection(3);
//                }

            }
        });

//        RadioGroup payMethodGroup = (RadioGroup) rootView.findViewById(R.id.pay_method);
//        payMethodGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//
//                switch (checkedId){
//                    case R.id.pay_method_school_card:
//                        payMethod = "1";
//                        break;
//                    case R.id.pay_method_bank_card:
//                        payMethod = "2";
//                        break;
//                    default:
//                        break;
//                }
//                Log.d("payMethod", payMethod);
//            }
//        });

        Button submitBtn = (Button) rootView.findViewById(R.id.submit_btn);
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(getContext(), "暂未支持充值,敬请期待", Toast.LENGTH_SHORT).show();
                loadingView.show();

                new Thread(){
                    @Override
                    public void run() {
                        super.run();

                        try {
                            String urlStr = getString(R.string.domain_name) + "/userBalance.php";
                            URL url = new URL(urlStr);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestProperty("Cookie", session);
                            connection.setDoInput(true);
                            connection.setDoOutput(true);
                            connection.connect();
                            String result = "";
                            if (connection.getResponseCode() == 200){
                                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                String line;
                                while ((line = br.readLine()) != null) result += line;
                                Log.d("result", result);

                                JSONTokener jsonParser = new JSONTokener(result);
                                JSONObject jsonObject = (JSONObject) jsonParser.nextValue();
                                String userBalanceStr = jsonObject.getString("raw");
                                Double userBalance = Double.parseDouble(userBalanceStr);
                                userBalanceHandler.obtainMessage(0, userBalance).sendToTarget();
                                br.close();

                            }else {
                                userBalanceHandler.obtainMessage(1, "出错").sendToTarget();
                            }
                            connection.disconnect();

                        } catch (IOException | JSONException e) {
                            e.printStackTrace();
                            userBalanceHandler.obtainMessage(1, "出错").sendToTarget();
                        }
                    }
                }.start();
            }

        });

        return rootView;
    }

    private void getElectrick(){
        balanceLabel.setText(getString(R.string.balance_placeholder));
        updateTimeLabel.setText("请稍后...");
        if (buildID != null && floorID != null && dormID != null) {
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    try {
                        //"building=\(build!)&floor=\(floor!)&room=\(room!)"
                        String postData = "building="+buildID+"&floor="+floorID+"&room="+dormID;
                        String urlStr = getString(R.string.domain_name) + "/getBalance.php";
                        URL url = new URL(urlStr);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("POST");
                        connection.setRequestProperty("Cookie", session);
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        PrintWriter pw = new PrintWriter(connection.getOutputStream());
                        pw.print(postData);
                        pw.flush();
                        connection.connect();
                        String result = "";
                        if (connection.getResponseCode() == 200){
                            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                result += line;
                            }
                            Log.d("result", result);
                            String[] data = result.split(",");
                            if (data.length > 1){
                                balanceHandler.obtainMessage(0, data).sendToTarget();
                            }else {
                                Log.e("data", "illegal");
                                balanceHandler.obtainMessage(1, "").sendToTarget();
                            }
                            reader.close();
                        }else {
                            throw new Exception("网络错误");
                        }
                        pw.close();
                        connection.disconnect();
                    }catch (Exception err) {
                        err.printStackTrace();
                        balanceHandler.obtainMessage(1, "").sendToTarget();
                    }
                }
            }.start();
        }else {
            dormLabel.setText(getString(R.string.unselected));
            updateTimeLabel.setText("");
        }
    }

    private void goPay(){
        loadingView.show();
        new Thread(){
            @Override
            public void run() {
                super.run();
                SharedPreferences preferences = getContext().getSharedPreferences("dorm", Context.MODE_PRIVATE);
                String buildName = preferences.getString("buildNameRaw", null);
                String floorName = preferences.getString("floorNameRaw", null);
                String roomName = preferences.getString("roomNameRaw", null);
                if (buildName != null && floorName != null && roomName != null){
                    String postData = "dormId="+dormID+"&buildName="+buildName+"&floorName="+floorName+"&roomName="+roomName+"&money="+payAmount;
                    String urlStr = getString(R.string.domain_name)+"/ecpay.php";
                    try {
                        URL url = new URL(urlStr);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("POST");
                        connection.setRequestProperty("Cookie", session);
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        PrintWriter pw = new PrintWriter(connection.getOutputStream());
                        pw.print(postData);
                        pw.flush();
                        connection.connect();
                        String result = "";
                        if (connection.getResponseCode() == 200){
                            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                result += line;
                            }
                            Log.d("result", result);
                            reader.close();
                            JSONTokener jsonParser = new JSONTokener(result);
                            JSONObject jsonObject = (JSONObject) jsonParser.nextValue();
                            int resultCode = jsonObject.getInt("code");
                            if (resultCode == 200){
                                payHandler.obtainMessage(0, "充值成功").sendToTarget();
                            }else {
                                String msg = jsonObject.getString("msg") != null ? jsonObject.getString("msg") : "发生了错误";
                                payHandler.obtainMessage(1, msg).sendToTarget();
                            }

                        }else {
                            payHandler.obtainMessage(1, "发生了错误").sendToTarget();
                        }
                        pw.close();
                        connection.disconnect();
                    } catch (Exception e) {
                        payHandler.obtainMessage(1, "发生了错误").sendToTarget();
                        e.printStackTrace();
                    }
                }else {
                    Toast.makeText(getContext(), "发生了错误", Toast.LENGTH_LONG).show();
                }

            }
        }.start();
    }

    @SuppressLint("HandlerLeak")
    private class BalanceHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0){
                String[] data = (String[]) msg.obj;
                balanceLabel.setText(data[0]);
                updateTimeLabel.setText("更新时间: "+data[1]);
            }else {

                Toast.makeText(getContext(), "发生了错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private class UserBalanceHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadingView.hide();
            if (msg.what == 0){
                Double data = (Double) msg.obj;

                try{
                    if (payAmount < 1){
                        Toast.makeText(getContext(), "金额太小", Toast.LENGTH_SHORT).show();
                    }else if (payAmount > 1000){
                        Toast.makeText(getContext(), "金额太大", Toast.LENGTH_SHORT).show();
                    }else {
                        SharedPreferences preferences = getContext().getSharedPreferences("dorm", Context.MODE_PRIVATE);
                        String content =
                                "宿舍: "+dormLabel.getText()
                                +"\n("+preferences.getString("floorNameRaw","")+", "+preferences.getString("roomNameRaw", "")
                                +")\n余额: "+data.toString()
                                +"元\n充值金额: "+String.valueOf(payAmount)+"元";
                        if (data.intValue() >= payAmount){
                            new AlertDialog.Builder(getContext())
                                    .setTitle("电费充值")
                                    .setMessage(content)
                                    .setPositiveButton("充值", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Log.d("dialog", "pay");
                                            dialog.dismiss();
                                            goPay();
                                        }
                                    })
                                    .setNegativeButton("取消", null)
                                    .show();
                        }else {
                            new AlertDialog.Builder(getContext())
                                    .setTitle("电费充值")
                                    .setMessage(content)
                                    .setPositiveButton("余额不足", null)
                                    .show();
                        }

                    }
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(getContext(), "金额不对", Toast.LENGTH_SHORT).show();
                }



            }else {
                Toast.makeText(getContext(), "发生了错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private class PayHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadingView.hide();
            if (msg.what == 0){
                Toast.makeText(getContext(), "充值成功", Toast.LENGTH_SHORT).show();
            }else {
                String message = "发生了错误";
                try {
                    message = (String) msg.obj;
                }catch (Exception e){
                    e.printStackTrace();
                }
                new AlertDialog.Builder(getContext())
                        .setTitle("提示")
                        .setMessage(message)
                        .show();
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.exit_login:
                Log.d("balanceFragment", "exitLogin");
                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, new LoginFragment())
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
                        .commit();
                return true;
            case R.id.exit_clear:
                Log.d("balanceFragment", "exitClear");
                SharedPreferences.Editor editor = getContext().getSharedPreferences("user", Context.MODE_PRIVATE).edit();
                editor.clear();
                editor.apply();
                SharedPreferences.Editor editor1 = getContext().getSharedPreferences("dorm", Context.MODE_PRIVATE).edit();
                editor1.clear();
                editor1.apply();
                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, new LoginFragment())
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)
                        .commit();
            default:
                return super.onOptionsItemSelected(item);
        }
    }


}
